package com.iversonx.proxy.example_1.controller.v1;

import com.iversonx.proxy.example_1.domain.RequestInfo;
import com.iversonx.proxy.example_1.service.MetricsCollector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 *
 **/
@Component
public class UserController {
    private final Logger logger = LoggerFactory.getLogger(UserController.class);
    
    @Autowired
    private MetricsCollector metricsCollector;
    
    public void login() {
        logger.info("Start login()");
        long start = System.currentTimeMillis();
        
        // 模拟登录逻辑
        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(5));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    
        long end = System.currentTimeMillis();
    
        // 记录响应时间
        recordRequest("login", start, end);
        logger.info("End login()");
    }
    
    public void register() {
        logger.info("Start register()");
        long start = System.currentTimeMillis();
    
        // 模拟登录逻辑
        try {
            TimeUnit.SECONDS.sleep(new Random().nextInt(5));
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    
        long end = System.currentTimeMillis();
    
        // 记录响应时间
        recordRequest("register", start, end);
        logger.info("End register()");
    }
    
    private void recordRequest(String type, long start, long end) {
        RequestInfo requestInfo = new RequestInfo();
        requestInfo.setType(type);
        requestInfo.setStartTime(start);
        requestInfo.setResponseTime(end);
        metricsCollector.recordRequest(requestInfo);
    }
}
